# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2021/10/19 10:06
# @Author  : zuodengbo
# @Email   : zuodb@amoydx.com
# @File    : time_task
# @Software: PyCharm
import time
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from tasks.models import Crontab
from utils.common import str2fun
# from celery import Celery
#
# celery_app = Celery("tasks", broker="redis://127.0.0.1:6379/12", backend="redis://127.0.0.1:6379/13")

schedule = BlockingScheduler()


# @schedule.scheduled_job("interval", seconds=2)
# @celery_app.task
def time_job():
    """
    demo
    :return:
    """
    print("1-定时打印：", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))


def time_2():
    """

    :return:
    """
    print("2-定时打印：", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))


async def all_jobs():
    """
    从数据库获取定时任务配置
    :return:
    """
    jobs = list()
    scheduler = AsyncIOScheduler()
    crons = await Crontab.filter(status=1).all()
    if crons:
        for cron in crons:
            task_name = cron.task_name  # tasks.tasks.time_job
            timer = cron.timer
            task_func = str2fun(task_name)
            job = scheduler.add_job(task_func, CronTrigger.from_crontab(timer))
            jobs.append(job)
        scheduler.start()
    

if __name__ == '__main__':
    # celery_app.worker_main()
    time_job()